package com.apache.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

/**
 * description: 系统工具类
 * 动态获取配置文件配置信息
 */
public class SystemTools {

	private static SystemTools instance;

	private long lastUpateTime = 0l;//最后修改时间

	private Map<String, String> constant = new HashMap<String, String>();//存放系统配置参数

	/**
	  * description: 启用单例模式
	  * @return
	 */
	public synchronized static SystemTools getInstance() {
		if (null == instance) {
			instance = new SystemTools();
		}
		return instance;
	}

	/**
	  * description: 加载配置文件
	 */
	private void initConfig(String propFilePath) {
		propFilePath = this.getClassLoaderPath() + propFilePath;
		File oldfile = new File(propFilePath);

		long lastModletime = oldfile.lastModified();
		if (lastUpateTime < lastModletime) {//有更新从新加载
			lastUpateTime = lastModletime;
			Properties prop = getProperties(propFilePath);
			Map<String, String> map = new HashMap<String, String>((Map) prop);
			Set propertySet = map.entrySet();
			for (Object o : propertySet) {
				Map.Entry entry = (Map.Entry) o;
				constant.put(entry.getKey().toString(), entry.getValue().toString());
			}
		}
	}

	public String getClassLoaderPath() {
		String path = "";
		URL classLoaderUrl = Thread.currentThread().getContextClassLoader().getResource("");
		if (null == classLoaderUrl) {
			path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
		} else {
			path = classLoaderUrl.getPath();
		}
		if (StrUtil.isNotNull(path)) {
			if (path.startsWith(File.separator) || path.startsWith("/")) {
				String systemType = getSystemType();
				if ("windows".equals(systemType))
					path = path.substring(1);
			}
		}
		return path;
	}

	/**
	 * 获取操作系统类型
	 *
	 * @return 返回操作系统类型
	 */
	public String getSystemType() {
		String result = "windows";
		if (System.getProperty("os.name").equals("Linux")) {
			result = "linux";
		} else if ("Mac OS X".equals(System.getProperty("os.name"))) {
			result = "Mac OS X";
		}
		return result;
	}

	public Properties getProperties(String filePath) {
		Properties prop = null;
		FileInputStream fileInput = null;
		try {
			File file = new File(filePath);
			if (file.exists()) {// 判断文件夹是否存在
				prop = new Properties();
				fileInput = new FileInputStream(filePath);
				prop.load(fileInput);
			}
		} catch (IOException e) {
			System.out.println("文件读取失败 key=" + e.getMessage());
		} finally {
			try {
				if (prop != null)
					fileInput.close();
			} catch (Exception e) {
				System.out.println("文件流关闭失败 key=" + e.getMessage());
			}
		}
		return prop;
	}

	/**
	  * description: 根据指定的KEY获取相应配置信息
	  * @param key   指定的KEY
	  * @return
	 */
	public String getConstant(String propFilePath, String key) {
		initConfig(propFilePath);
		return constant.get(key);
	}

	public Map<String, String> getAllProperty(String propFilePath) {
		initConfig(propFilePath);
		return constant;
	}

	private final String[] mobileAgents = { "iphone", "android", "phone", "mobile", "wap", "netfront", "java",
			"opera mobi", "opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry",
			"dopod", "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma",
			"docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos",
			"techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem",
			"wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos", "pantech",
			"gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320", "240x320", "176x220",
			"w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell",
			"cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi", "keji", "leno",
			"lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp",
			"nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port", "prox", "qwap", "sage",
			"sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony",
			"sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda", "wap-", "wapa",
			"wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-", "Googlebot-Mobile" };

	public boolean JudgeIsMoblie(HttpServletRequest request) {
		boolean isMoblie = false;
		String user_agent = request.getHeader("User-Agent");
		if (StrUtil.isNotNull(user_agent)) {
			for (String mobileAgent : mobileAgents) {
				if (user_agent.toLowerCase().indexOf(mobileAgent) >= 0) {
					isMoblie = true;
					break;
				}
			}
		}
		if (!isMoblie) {
			String mobileType = request.getParameter("User_Agent");
			if (StrUtil.isNotNull(mobileType)) {
				isMoblie = true;
			}
		}
		return isMoblie;
	}

	public static void main(String[] args) {

	}
}
